package com.apes.scm.account.creditLine.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.DateUtil;
import com.apes.scm.account.creditLine.service.CreditLineService;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Objects;


@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = com.apes.scm.account.creditLine.model.CreditLine.CONST_TABLE_NAME)
public class CreditLine extends Model {
    public static final String CONST_TABLE_NAME = "acc_credit_line";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "信用额度调整单", prefix = "C")
    @Comment("调整单号")
    private String id; //信用额度调整单

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company; //公司

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("部门")
    private Dept dept; //部门

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "partner_id", referencedColumnName = "id", nullable = false)
    @Comment("业务伙伴")
    private PartyRole partner; //业务伙伴

    @States(name = "单据状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "repeal", name = "终止"),
            @State(id = "approve", name = "审核")})
    @Column(name = "state", length = 10, nullable = false)
    private String state; //状态

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId; //审核

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate; //审核日期

    @Column(name = "note", length = 250)
    @Comment("备注")
    private String note; //备注

    @Column(name = "incurred", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("发生金额")
    private double incurred;   // 发生金额

    @Column(name = "history_line", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("历史额度")
    private double historyLine = 0; //历史额度

    public double getHistoryLine() {
        if(!state.equals("create")) return historyLine;
        CreditLineService creditLineService = SpringManager.getBean(CreditLineService.class);
        return creditLineService.findLedgerByType(company,partner,"credit").get("credit");
    }

    public double getBalanceLine() {
        if(!state.equals("create")) return balanceLine;
        return historyLine + incurred;
    }

    //202206字段取消
    @Column(name = "balance_line", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("结余额度")
    private double balanceLine = 0; //结余额度

    //202206字段取消
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "valid_date_end")
    @Comment("有效期止")
    private Date validDateEnd;

    @Column(name = "account_period", columnDefinition = ApesConst.FIELD_16_4)
    @Comment("账期")
    private Integer accountPeriod = 0;   // 账期（7天、15天、30天、60天、90天、120天、180天、365天、9999天）

    @Column(name = "history_account_period", columnDefinition = ApesConst.FIELD_16_4)
    @Comment("历史账期")
    private Integer historyAccountPeriod = 0;   //历史账期（7天、15天、30天、60天、90天、120天、180天、365天、9999天）


    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    @Transient
    private String text;

    @Transient
    public String getText() {
        if(this.getAccountPeriod() == null) return null;
        String enumeration = "";
        Enumeration paymentPeriod = SpringManager.getBean(EnumerationRepository.class).findByDescriptionAndTypeId(this.getAccountPeriod().toString(), "paymentPeriod");

        if(Objects.isNull(paymentPeriod)){
            enumeration = getAccountPeriod().toString();
        }else{
            enumeration=paymentPeriod.getDescription();
        }
        return enumeration;
    }
}
